<template>
  <div class="container">
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="add">新建</el-button>
        <!-- <el-button type="success" @click="importData">报检</el-button> -->
        <el-button type="success" @click="rk">申请入库</el-button>
        <el-button type="warning" @click="edit">编辑</el-button>

      </div>
      <el-table :data="tableData" border class="eltable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="dhzt" label="状态" width="80">
          <template #default="{ row }">
            <span v-if="row.dhzt === 1">未到货</span>
            <span v-else-if="row.dhzt === 2">已到货</span>
          </template>
        </el-table-column>
        <el-table-column prop="dhcode" label="到货单号"></el-table-column>
        <el-table-column prop="yclcg_code" label="采购单号"></el-table-column>
        <el-table-column prop="yclcg_time" label="采购日期">
          <template #default="{ row }">
            {{ formatDate(row.yclcg_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="yclcg_ry" label="采购人员"></el-table-column>
        <el-table-column prop="djbz" label="备注"></el-table-column>
        <el-table-column prop="user_name" label="创建人"></el-table-column>
        <el-table-column prop="create_time" label="创建时间">
          <template #default="{ row }">
            {{ formatDate(row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="text" @click="dhRow(row)">到货数量</el-button>
            <el-button type="text" @click="editRow(row)">详情</el-button>
            <el-button type="text" @click="deleteRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper">
      </el-pagination>
    </div>
  </div>

  <el-dialog v-model="dialogVisible" title="到货数量" width="800" :before-close="handleClose">
    <el-form :model="form" class="demo-form-inline" :rules="rules" ref="formRef">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="采购数量" :label-width="formLabelWidth" prop="yclcg_sl">
            <el-input v-model="form.yclcg_sl" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已到货数量" :label-width="formLabelWidth" prop="yclcg_dhsl">
            <el-input v-model="form.yclcg_dhsl" placeholder="请输入已到货数量" type="number" clearable
              @input="handleDhslInput"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
  <el-dialog v-model="dialogVisible1" title="到货单详情" width="80%" @close="handleClose">
    <div class="delivery-detail-container">
      <!-- 表单区域 -->
      <el-form :model="formData" label-position="right" label-width="100px" size="large" style="font-size: 100px;">
        <el-row :gutter="18">
          <el-col :span="6">
            <el-form-item label="*到货单号:">
              <el-input v-model="formData.dhcode" placeholder="请输入到货单号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购订单号:">
              <el-input v-model="formData.yclcg_code" placeholder="请输入采购订单号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购日期:">
              <el-input v-model="formData.yclcg_time" placeholder="请输入采购日期" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注:">
              <el-input v-model="formData.bz" placeholder="请输入备注" disabled />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <!-- 表格区域 -->
      <div class="table-section">
        <h3>到货明细</h3>
        <el-table :data="tableDatawl" border style="width: 100%" height="300">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="wl_code" label="物料编码" />
          <el-table-column prop="wl_name" label="物料名称" />
          <el-table-column prop="dictionary_name" label="物料分类" />
          <el-table-column prop="dw_name" label="物料单位" />
          <el-table-column prop="ks_name" label="供应商" />
          <el-table-column prop="yclcg_sl" label="计划到货数量" />
          <el-table-column prop="yclcgxq_ydhsl" label="到货数量" />
        </el-table>
      </div>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>


<script>
import axios from 'axios';
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  setup() {
    const searchKey = ref('');
    const treeData = ref([]);
    const defaultProps = {
      children: 'children',
      label: 'label',
    };

    const tableData = ref([]);

    const selectedFilter = ref('');
    const searchTable = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(3);
    const dialogVisible = ref(false)
    const dialogVisible1 = ref(false)
    const currentSelection = ref([]);
    const form = ref({
      yclcg_sl: '',
      yclcg_dhsl: '',
    });
    const formData = reactive({
      dhcode: '',
      yclcg_code: '',
      yclcg_time: '',
      bz: '',
    });
    const tableDatawl = ref([]);
    function sx() {
      axios.get('/api/Rm_yclcg/Getdh?PageNumber=' + currentPage.value + '&pageSize=' + pageSize.value)
        .then((response) => {
          console.log(response.data);
          tableData.value = response.data.rm_Yclcgs;
          totalItems.value = response.data.zon;
        }).catch((error) => {
          console.error('Error:', error);
        });
    }
    sx()
    const dhRow = (row) => {
      console.log(row);
      form.value = row;
      if (row.yclcg_sl == row.yclcgxq_ydhsl) {
        ElMessage.error("已到货，无需再次到货");
        return;
      }
      dialogVisible.value = true;
    }
    const handleDhslInput = (value) => {
      if (value > form.yclcg_sl) {
        form.yclcg_dhsl = form.yclcg_sl;
      }
    };
    const submitForm = async () => {
      if (form.value.yclcg_dhsl > form.value.yclcg_sl) {
        ElMessage.error("到货数量不能大于采购数量");
        return;
      } else {
        console.log(form.value);
        const response = await axios.put('/api/Rm_yclcgxq/UpDhsl?ydhsl=' + form.value.yclcg_dhsl + '&code=' + form.value.yclcg_code);
        console.log(response);
        if (response.data == 1) {
          //console.log('修改成功');
          const response = await axios.put('/api/Rm_yclcg/UpZt?code=' + form.value.yclcg_code);
          console.log(response.data);
          if (response.data == 1) {
            console.log('修改成功');
            ElMessage.success('已到货');
            dialogVisible.value = false;
            sx();
          }
        }
      }
    }

    // 处理选中行变化
    const handleSelectionChange = (selection) => {
      console.log('选中的行:', selection);
      currentSelection.value = selection;

    };
    const rk = () => {
      currentSelection.value.forEach(row => {
        console.log(row); // 遍历每一行的 yclcg_code;
        axios.put('/api/Rm_yclcg/UpRk', {
          yclcg_code: row.yclcg_code,
          rkcode: row.rkcode,
          rkzt: row.rkzt,
          rklx: row.rklx,
          jhrktime: row.jhrktime // 确保时间格式正确
        })
          .then((response) => {
            ElMessage.success("已申请");
            console.log(response.data);
          })
          .catch((error) => {
            console.error('Error:', error.response.data);
          });

      });
    }
    // 格式化日期函数
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')}`;
    };

    const edit = () => {
      // 编辑逻辑  
    };



    const query = () => {
      // 查询逻辑  
      console.log('Querying with:', searchTable.value);
    };
    // 编辑行逻辑  
    const editRow = (row) => {

      console.log('Editing row:', row);
      dialogVisible1.value = true;
      formData.dhcode = row.dhcode;
      formData.yclcg_code = row.yclcg_code;
      formData.yclcg_time = row.yclcg_time;
      formData.bz = row.djbz;
      axios.get('/api/Rm_yclcgxq/Getdh?code=' + row.yclcg_code)
        .then((response) => {
          console.log(response.data);
          tableDatawl.value = response.data;
        }).catch((error) => {
          console.error('错误:', error);
        })

    };

    const deleteRow = (row) => {
      // 删除行逻辑  
      console.log('Deleting row:', row);
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      // 分页逻辑  
      console.log('Current page:', page);
      sx();
    };

    // 确保所有函数都被返回  
    return {
      searchKey,
      treeData,
      defaultProps,
      tableData,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      edit,
      query,
      editRow,
      deleteRow,
      handleCurrentChange,
      dialogVisible,
      dialogVisible1,
      dhRow,
      form,
      submitForm,
      handleSelectionChange,
      formData,
      tableDatawl,
      rk,
      currentSelection,
      handleDhslInput,
      formatDate
    };
  },
};
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 87vh;
}

.sidebar {
  height: 100%;
  width: 30vh;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 90%;
}

.letree {
  height: 97%;
}
</style>